// -----------------------------------------------------------------------
//  <copyright file="ResourceExtractorBase.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2024 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2024/12/7 13:51:57</last-date>
// -----------------------------------------------------------------------

namespace DaprPlus.Authorization;

/// <summary>
/// 资源信息提取器基类
/// </summary>
/// <param name="provider"></param>
public abstract class ResourceExtractorBase(IServiceProvider provider) : IResourceExtractor
{
    /// <summary>
    /// 获取 资源类型
    /// </summary>
    public abstract ResourceType ResourceType { get; }

    /// <summary>
    /// 提取资源信息
    /// </summary>
    /// <param name="serviceName">服务名称</param>
    /// <returns></returns>
    public async Task<IResource[]> ExtractAsync(string serviceName)
    {
        var resources = await ExtractCoreAsync(serviceName);

        await SyncAsync(resources, serviceName);

        return resources;
    }

    /// <summary>
    /// 重写以实现资源提取
    /// </summary>
    /// <param name="serviceName"></param>
    /// <returns></returns>
    protected abstract Task<IResource[]> ExtractCoreAsync(string serviceName);

    /// <summary>
    /// 同步资源信息
    /// </summary>
    /// <param name="resources">资源信息</param>
    /// <param name="serviceName">服务名称</param>
    /// <returns></returns>
    protected virtual Task SyncAsync(IResource[] resources, string serviceName)
    {
        return provider.ExecuteScopedWorkAsync(async scopedProvider =>
        {
            var synchronizer = scopedProvider.GetRequiredService<IResourceSynchronizer>();
            await synchronizer.SyncAsync(serviceName, ResourceType, resources);
        });
    }
}
